import type { Router } from 'vue-router';
import NProgress from 'nprogress';

import { useUserStore, useAppStore } from '@/store';
import { isLogin } from '@/utils/auth';

export default function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach(async (to, _from, next) => {
    NProgress.start();
    const userStore = useUserStore();
    const appStore = useAppStore();

    // 是否需要登录
    if (!appStore.loginAuth) {
      // 不需要登录
      next();
      NProgress.done();
      return;
    }

    // 是否是白名单
    if (!to.meta.requiresAuth) {
      // 放行
      next();
      NProgress.done();
      return;
    }

    // 是否登录
    if (isLogin()) {
      try {
        await userStore.info();
        next();
      } catch (error) {
        userStore.logoutCallBack();
        // 跳转登录
        appStore.loginModal.visible = true;
        appStore.loginModal.to = to.name as string;
        next(false);
      }
    } else {
      // 跳转登录
      appStore.loginModal.visible = true;
      appStore.loginModal.to = to.name as string;
      next(false);
    }

    NProgress.done();
  });
}
